package com.wanbatv.wangwangba.util;

import android.app.AlertDialog;
import android.app.DownloadManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Environment;
import android.widget.Toast;

import com.wanbatv.wangwangba.model.entity.UpdataData;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by 俞亚楠 on 2016/7/29.
 */
public class UpdataDownload {
    Context context;
    String versionName;
    String updataUrl;
    int isForceUpdate;
    DownloadTaskReceiver receiver;
    public UpdataDownload(Context context){
        this.context=context.getApplicationContext();
    }
    Retrofit retrofit=new Retrofit.Builder()
            .addConverterFactory(GsonConverterFactory.create())
            .client(HeaderClient.genericClient())
            .build();
    GitUpdataService api=retrofit.create(GitUpdataService.class);
    public void updataApk(final String currVersion){
        receiver=new DownloadTaskReceiver();
        api.getUpdata(Product.flavor).enqueue(new Callback<UpdataData>() {
            @Override
            public void onResponse(Call<UpdataData> call, Response<UpdataData> response) {
                versionName=response.body().getData().getVersionName();
                updataUrl=response.body().getData().getApk();
                isForceUpdate=response.body().getData().getIsForce();
                if(Util.converVersionNameToInt(currVersion)<Util.converVersionNameToInt(versionName)){
                    AlertDialog.Builder builder = new AlertDialog.Builder(
                            context)
                            .setTitle("提示")
                            .setMessage("升级到最新版本")
                            .setPositiveButton(
                                    "确定",
                                    new AlertDialog.OnClickListener() {
                                        public void onClick(
                                                DialogInterface dialog,
                                                int which) {
                                            Toast.makeText(
                                                    context,
                                                    "开始下载！",
                                                    Toast.LENGTH_LONG)
                                                    .show();
                                            download("",
                                                    updataUrl,
                                                    "wangwangba",
                                                    "", 0);
                                        }
                                    });

                    if (isForceUpdate == 0) {
                        builder.setNegativeButton("取消",
                                new AlertDialog.OnClickListener() {

                                    @Override
                                    public void onClick(
                                            DialogInterface dialog,
                                            int which) {
                                        dialog.dismiss();
                                    }
                                });
                        builder.setCancelable(true);
                    } else {
                        builder.setCancelable(false);
                    }
                    builder.create();
                    builder.show();
                }
            }

            @Override
            public void onFailure(Call<UpdataData> call, Throwable t) {

            }
        });

    }
    public void download(String appId, String downloadUrl, String appName,
                         String appDesc, long appSize) {
        // 初始化DownloadTask实例
        DownloadTask aDownloadTask = new DownloadTask(appId,
                Uri.parse(downloadUrl), appName, appDesc, appSize);
        // 实例化DownloadManager.Request
        DownloadManager.Request request = new DownloadManager.Request(
                aDownloadTask.getDownloadURI());
        // 系统下载路径
        request.setDestinationInExternalFilesDir(context,
                Environment.DIRECTORY_DOWNLOADS, appName + ".apk");

        // request.setShowRunningNotification(true);
        // 向队列加载一个新的下载项
        DownloadManager downloadManager = ((DownloadManager) context
                .getSystemService(context.DOWNLOAD_SERVICE));
        long downloadId = downloadManager.enqueue(request);
        // 保存downloadId
        aDownloadTask.setDownloadId(downloadId);
        // 保存DownloadTask对象
        // tasks.add(aDownloadTask);
        // 过滤器 当前下载任务完成
        IntentFilter filter = new IntentFilter(
                DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        // 注册并监听过滤器
        context.registerReceiver(receiver, filter);
    }
}
